import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { Table, Tag, Button, notification } from 'antd'
export default function Audit() {
    const [dataSource, setdataSource] = useState([])
    const { roleId, region, username } = JSON.parse(localStorage.getItem('token'))
    useEffect(() => {
        query()
    }, [roleId, region, username])
    const query = () => {
        const roleObj = {
            '1': 'superadmin',
            '2': 'admin',
            '3': 'editor'
        }
        axios.get('/news?auditState=1&_expand=category').then(res => {
            const list = res.data
            setdataSource(roleObj[roleId] === 'superadmin' ? list : [...list.filter(i => i.author === username),
            ...list.filter(item => item.region === region && roleObj[item.roleId] === 'editor')])
        })
    }
    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'title',
            render: (title, item) => {
                return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
            }
        },
        {
            title: '作者',
            dataIndex: 'author',

        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            render: (category) => <div>{category.title}</div>

        },
        {
            title: '审核状态',
            dataIndex: 'auditState',
            render: (auditState) => {
                const colorList = ['', 'orange', 'green', 'red']
                const curList = ['', '待审核', '审核成功', '审核失败']
                return < Tag color={colorList[auditState]}>  {curList[auditState]}</Tag>
            }
        },
        {
            title: '操作',
            render: (item) => {
                return <div>
                    <Button type='primary' style={{ marginRight: '10px' }} onClick={() => handleAudit(item, 2, 1)}>通过</Button>
                    <Button danger onClick={() => handleAudit(item, 3, 0)}>驳回</Button>
                </div >
            }
        },
    ]
    const handleAudit = (item, auditState, pubilshState) => {
        axios.patch(`/news/${item.id}`, { auditState, pubilshState }).then(res => {
            query()
            notification.info({
                message: '通知',
                description: `您可以通过[审核管理/审核列表]中查看你的新闻`,
                placement: 'bottomRight'
            })
        })
    }
    return (
        <div>
            <Table dataSource={dataSource} columns={columns} pagination={{
                pageSize: 5
            }} rowKey={(item) => item.id} />
        </div>
    )
}
